﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AionCxxLibrary.Packets;
using WorldServer.Services;
using AionCxxLibrary.Utilities;
using WorldServer.Packets.Server;
using AionCxxLibrary.Enums;
using AionCxxLibrary.Models;
using AionCxxLibrary.DAO;
using WorldServer.Data;
using WorldServer.DAO;

namespace WorldServer.Packets.Client
{
    public class CPkt_CharacterList : AionClientPacket
    {
        public override void ProcessPacket()
        {
            int KeyWorld2 = ReadInt();

            if (KeyWorld2 != ((WorldConnection)Connection).Keys[2])
            {
                Log.Hack(Connection.GetRemoteIP() + " (" + Connection.account.Name + ") trying to load characters with invalid KeyWorld2!");
                Connection.Close();
            }

            Connection.SendPacket(new SPkt_CharacterList());
        }
    }

    public class CPkt_CharacterCreate : AionClientPacket
    {
        public override void ProcessPacket()
        {
            WorldConnection wc = ((WorldConnection)Connection);
            int KeyWorld2 = ReadInt();
            if (KeyWorld2 != wc.Keys[2])
            {
                Log.Hack("Attempt to create character with wrong KeyWorld2!");
                Connection.Close();
                return;
            }

            string unk = ReadString();
            Log.Debug("CreateCharacterUnkStr=" + unk);

            string name = Utility.ConvertCharacterName(ReadString());
            ReadBytes(50 - (name.Length * 2));
            byte gender = (byte)ReadInt();
            Race race = (Race)ReadInt();
            CharacterClass clazz = (CharacterClass)ReadInt();

            CharacterCreateResponse response = CharacterCreateResponse.Failed;
            TCharacter character = null;

            if (name.Length > 32)
                response = CharacterCreateResponse.InvalidName;
            else if (((int)clazz % 3) != 0)
                response = CharacterCreateResponse.DatabaseError;
            else if (CharacterDAO.SelectCharacterCountByAccount(Connection.account.ID) >= 8)
                response = CharacterCreateResponse.LimitExceeded;
            else if (CharacterDAO.CheckNameExists(name))
                response = CharacterCreateResponse.NameAlreadyUsed;
            else
            {
                TCharacterAppearance appearance = new TCharacterAppearance();
                appearance.Voice = (byte)ReadInt();
                appearance.RGB_Skin = ReadInt();
                appearance.RGB_Hair = ReadInt();
                appearance.RGB_Eye = ReadInt();
                appearance.RGB_Lip = ReadInt();
                appearance.Face = ReadByte();
                appearance.Hair = ReadByte();
                appearance.Decoration = ReadByte();
                appearance.Tattoo = ReadByte();
                appearance.FaceContour = ReadByte();
                appearance.Expression = ReadByte();
                ReadByte();
                appearance.Jawline = ReadByte();
                appearance.Forehead = ReadByte();
                appearance.EyeHeight = ReadByte();
                appearance.EyeSpace = ReadByte();
                appearance.EyeWidth = ReadByte();
                appearance.EyeSize = ReadByte();
                appearance.EyeShape = ReadByte();
                appearance.EyeAngle = ReadByte();
                appearance.BrowHeight = ReadByte();
                appearance.BrowAngle = ReadByte();
                appearance.BrowShape = ReadByte();
                appearance.Nose = ReadByte();
                appearance.NoseBridge = ReadByte();
                appearance.NoseWidth = ReadByte();
                appearance.NoseTip = ReadByte();
                appearance.Cheek = ReadByte();
                appearance.LipHeight = ReadByte();
                appearance.MouthSize = ReadByte();
                appearance.LipSize = ReadByte();
                appearance.Smile = ReadByte();
                appearance.LipShape = ReadByte();
                appearance.JawHeight = ReadByte();
                appearance.ChinJut = ReadByte();
                appearance.EarShape = ReadByte();
                appearance.HeadSize = ReadByte();
                appearance.Neck = ReadByte();
                appearance.NeckLength = ReadByte();
                appearance.ShoulderSize = ReadByte();
                appearance.Torso = ReadByte();
                appearance.Chest = ReadByte();
                appearance.Waist = ReadByte();
                appearance.Hips = ReadByte();
                appearance.ArmThickness = ReadByte();
                appearance.HandSize = ReadByte();
                appearance.LegThickness = ReadByte();
                appearance.LegLength = ReadByte();
                appearance.FacialRate = ReadByte();
                ReadByte();
                appearance.ArmLength = ReadByte();
                appearance.FeetSize = ReadByte();
                appearance.Shoulders = ReadByte();
                appearance.FaceShape = ReadByte();

                ReadByte();
                ReadByte();
                ReadByte();

                appearance.Height = ReadFloat();

                character = new TCharacter();
                character.AccountID = Connection.account.ID;
                character.Appearance = appearance;
                character.Class = clazz;
                character.Gender = gender;
                character.Level = 1;
                character.Name = name;
                character.Position = Datastore.CharactersInitialData.BirthPoints[(int)race].To4D();
                character.Race = race;
                character.WorldID = Datastore.CharactersInitialData.BirthPoints[(int)race].WorldID;

                if (!CharacterService.CreateCharacter(character) || !ItemService.CreateInitialItems(character))
                    response = CharacterCreateResponse.DatabaseError;
                else
                {
                    CharacterDAO.InsertSettingsNull(character.ID);
                    response = CharacterCreateResponse.Success;
                }

            }

            Connection.SendPacket(new SPkt_CharacterCreate(character, response));

        }
    }

    public class CPkt_CharacterCheckName : AionClientPacket
    {
        public override void ProcessPacket()
        {
            string name = ReadString();
            CharacterCreateResponse response = CharacterDAO.CheckNameExists(name) ? CharacterCreateResponse.NameAlreadyUsed : CharacterCreateResponse.Success;
            Connection.SendPacket(new SPkt_CharacterCheckName(response));
        }
    }

    public class CPkt_CharacterSelect : AionClientPacket
    {
        public override void ProcessPacket()
        {
            int charId = ReadInt();

            TCharacter character = CharacterService.LoadCharacterTemplate(charId);

            if (character == null || character.AccountID != Connection.account.ID)
            {
                Log.Hack(Connection.GetRemoteIP() + " tries to enter world with character " + charId + " either not existing or not on his account!");
                return;
            }

            WorldConnection wc = (WorldConnection)Connection;
            CharacterService.OnCharacterSelect(ref wc, character);

        }
    }

    public class CPkt_CharacterDelete : AionClientPacket
    {
        public override void ProcessPacket()
        {
            int WorldKey2 = ReadInt();
            int CharacterID = ReadInt();

            TCharacter tc = CharacterDAO.SelectCharacterTemplate(CharacterID);

            if (tc == null)
            {
                Log.Hack(Connection.GetRemoteIP() + " [acct=" + Connection.account.Name + "] trying to delete inexistant character " + CharacterID);
                return;
            }

            if (WorldKey2 != ((WorldConnection)Connection).Keys[2] || tc.AccountID != Connection.account.ID)
            {
                Log.Hack(Connection.GetRemoteIP() + " [acct=" + Connection.account.Name + "] trying to delete character " + CharacterID + " not on his account!");
                return;
            }

            // TODO remove from legion
            // TODO disband legion if player was last of him
            // TODO else, select a tribun, then centurion, then legionary then newbie for role of brigade general

            ItemDAO.DeleteItems(CharacterID);
            CharacterDAO.DeleteCharacter(CharacterID);
            Connection.SendPacket(new SPkt_CharacterDelete(CharacterID));
        }
    }

}
